from flask import Blueprint,request,jsonify,redirect
import json
from dbs import dbs


bp_login=Blueprint('login',__name__)


@bp_login.route('/login',methods=['POST','GET'])
def login():
    if request.method == 'POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        sql = 'select * from lusers where username = "%s"' % (data['username'])
        res = dbs.findone(sql)
        if res:
            if res['password']==data['password']:
                return jsonify({'code': 200, 'userid': res['id'],'username':res['username']})
            else:
                return jsonify({'code': 20011, 'mes': '密码错误'})
        else:
            return jsonify({'code': 20012, 'mes': '用户不存在'})

    elif request.method == 'GET':
        username = request.args.get('username')
        uid = request.args.get('uid')
        token = request.args.get('token')
        print(uid,username,token)
        sql = 'select id from lusers where username = "%s"'%(username)
        res = dbs.findone(sql)
        if res:
            sql1 = 'select * from sf_login where userid = %d and token = "%s" and uid = "%s"'%(int(res['id']),token,uid)
            res1 = dbs.findone(sql1)
            if res1:

                return jsonify({'code':200,'url':'http://localhost:8080/#/','userid':res1['id']})
            else:

                sql3 = 'select id,username from lusers where username = "%s"'%(username)
                res3 = dbs.findone(sql3)
                sql4 = 'insert into sf_login(userid,uid,token) values(%d,"%s","%s")'%(int(res3['id']),uid,token)
                dbs.update(sql4)
                return jsonify({'code':200,'url':'http://localhost:8080/#/','userid':int(res3['id']),'username':res3['username']})
        else:
            sql2 = 'insert into lusers(username) values("%s")' % (username)
            dbs.update(sql2)
            sql3 = 'select id,username from lusers where username = "%s"' % (username)
            res3 = dbs.findone(sql3)
            sql4 = 'insert into sf_login(userid,uid,token) values(%d,"%s","%s")' % (int(res3['id']), uid, token)
            dbs.update(sql4)
            return jsonify({'code': 200, 'url': 'http://localhost:8080/#/', 'userid': int(res3['id']),
                            'username': res3['username']})


@bp_login.route('/uidtoken',methods=['GET'])
def uidtoken():
    if request.method == 'GET':
        uid = '123456'
        token = 'abcdefg'
        # return redirect('http://127.0.0.1:5000/login/login?uid='+str(uid)+'&token='+token+'&username='+username)
        return jsonify({'code':200,'luid':uid,'ltoken':token})


        